package heima_bixiangdong.pro_con;

// 单生产单消费
// 资源类，属性：具有名称和编号；行为：对商品名称赋值和获取商品
class Resource {
    private String name;
    private int num = 1;
    private boolean flag = false;

    public synchronized void set(String name){
        if(flag){
            try {
                //System.out.println(flag+".......wait....");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name + num;
        num++;
        System.out.println(Thread.currentThread().getName() + "....生产者...." + this.name);
        flag = true;
        // 唤醒消费者
        this.notify();
    }

    public synchronized void out(){
        if(!flag){
            try {
                //System.out.println(flag+".......wait....");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "...消费者..." + this.name);
        flag = false;
        // 唤醒生产者
        this.notify();
    }
}

// 生产者线程需要执行的任务
class Producer implements Runnable {
    private Resource resource;

    public Producer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        while (true) {
            resource.set("面包");
        }
    }
}

// 消费者线程需要执行的任务
class Consumer implements Runnable {
    private Resource resource;

    public Consumer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        while (true){
            resource.out();
        }
    }
}

// 客户端程序
public class Demo1 {
    public static void main(String[] args) {
        //test1();
        test2();
    }

    private static void test2() {
        Resource resource = new Resource();
        // 生产者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource.set("面包");
                }
            }
        }).start();

        // 消费者线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    resource.out();
                }
            }
        }).start();
    }

    private static void test1() {
        Resource resource = new Resource();
        Producer producer = new Producer(resource);
        Consumer consumer = new Consumer(resource);
        Thread t1 = new Thread(producer);
        Thread t2 = new Thread(consumer);
        t1.start();
        t2.start();
    }
}
